<!DOCTYPE html>
<html layout:decorator="fragments/layout" th:with="index='good',son='brand'" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:layout="http://www.thymeleaf.org/" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <title>品牌管理</title>
    <style>
        .tag [data-role="remove"]::after {
            content: "x";
            padding: 0px 2px;
        }

        .tag [data-role="remove"] {
            margin-left: 8px;
            cursor: pointer;
        }

        .tag {
            margin-right: 5px;
        }

        .table-bordered>tbody>tr>td
        {
            border: 0px;
        }

        table.dataTable thead th
        {
            border: 0px;
        }
        table.dataTable.no-footer
        {
            border: 0px;
        }
    </style>
</head>
<body>
<div layout:fragment="modal">
    <div class="modal right fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="myModalLabel">添加品牌</h4>
                </div>
                <div class="modal-body">
                    <div class="box-body">
                        <div class="row">
                            <div class="tableTitle pull-left" style="font-size: 14px">基础信息</div>
                        </div>
                        <div class="row">
                            <div class="col-sm-12">
                                <div style="padding-top: 10px">
                                    logo</div>

                                <img id="c-cover" name="cover" width="200px" height="100px"src="http://placehold.it/100x100/e6e6e6/e6e6e6"/>
                                <input id="cc-cover" name="cover" hidden value=""/>
                                <i class="fa   fa-cloud-upload " id="c-selectfiles" style="font-size: 20px"></i>


                            </div>

                        </div>
                        <div class="form-group" hidden="">
                            <label class="col-sm-2 control-label"></label>
                            <div class="col-sm-8">
                                <div id="c-ossfile">你的浏览器不支持flash,Silverlight或者HTML5！</div>
                            </div>
                        </div>

                        <div class="row" style="padding-top: 10px">
                            <div class="col-sm-8">
                                <div class="form-group">
                                    <label>名称</label>
                                    <input class="form-control" id="a-name">
                                </div>
                            </div>
                        </div>
                        <div class="row" style="padding-top: 10px">
                            <div class="col-sm-8">
                                <div class="form-group">
                                    <label>英文名称</label>
                                    <input class="form-control" id="a-enName">
                                </div>
                            </div>
                        </div>
                        <div class="row" style="padding-top: 10px">
                            <div class="col-sm-8">
                                <div class="form-group">
                                    <label>别名</label>
                                    <input class="form-control" id="a-name">
                                </div>
                            </div>
                        </div>

                        <div class="row" style="padding-top: 10px">
                            <div class="col-sm-11">
                                <div class="form-group">
                                    <label>品牌简介</label>
                                    <textarea class="form-control" id="a-simpleDesc"></textarea>
                                </div>
                            </div>
                        </div>
                        <!--多图上传-->
                        <div style="margin-top: 10px; ">
                            <label>图片展示栏</label>
                            <i class="fa   fa-cloud-upload" id="m-selectfiles"
                               style="font-size: 30px"></i>
                            <i class="fa fa-folder" style="font-size: 30px">
                            </i>
                        </div>
                        <div class="row" style="padding-top: 10px">
                            <div class="col-sm-11"
                                 style="border: 1px solid rgba(0,0,0,0.1);padding: 0;margin-left: 15px">
                                <div id="m-imgContent">
                                    <div class="form-group" id="m-imgGroup">
                                        <div class="col-md-3 img-item" id="noPic"
                                             style="border: 1px solid rgba(86,61,124,.2);margin-left: 15px;margin-bottom: 15px;">
                                            <div class="row">
                                                <div class="col-md-2 no-padding">
                                                    <button type="button" class="move pull-right"
                                                            style="background: rgba(255, 255, 255, 0.3);border: transparent;visibility: hidden">
                                                        <i class="fa fa-angle-double-left"></i></button>
                                                </div>
                                                <div class="col-md-2 no-padding pull-right">
                                                    <button type="button" class="close pull-left" aria-hidden="true" style="visibility: hidden"
                                                            onclick="deleteSelf(this)">×
                                                    </button>
                                                </div>
                                            </div>
                                            <div class="row m-cover">
                                                <div class="col-md-12 mm-cover no-padding"><img
                                                        id="&quot; + option.imgId + &quot;"
                                                        src="http://placehold.it/100x100/e6e6e6/e6e6e6" height="100px"
                                                        width="100%" style="border-top: 1px solid rgba(86,61,124,.2);">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="form-group" hidden="true">
                            <label class="col-sm-2 control-label"></label>
                            <div class="col-sm-8">
                                <div id="m-ossfile">你的浏览器不支持flash,Silverlight或者HTML5！</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class=" btn btn-default">取消</button>
                    <button class=" btn btn-primary " onclick="addBrand()">确认</button>
                </div>
            </div>
        </div>
        <!-- end 弹出层 moda -->
    </div>
</div>
<div layout:fragment="content">

    <script type="text/javascript" th:src="@{/js/imageUploader.js}"></script>
    <script type="text/javascript" th:src="@{/js/plupload/js/plupload.full.min.js}"></script>
    <script type="text/javascript" th:src="@{/js/alioss/uploads.js}"></script>
    <section class="content">
        <div class="box" style="margin-top: 20px">
            <div class="box-body" id="search-form">
                <div style="font-size: 16px;padding-top: 10px;padding-bottom: 10px ;display: inline">品牌管理</div>
                <!--<div class="pull-right" style="font-size: 12px;display: inline;color:#457ED8;cursor:pointer"-->
                     <!--id="moreSearch">高级查询-->
                <!--</div>-->
                <div class="row" style="padding-top: 10px">
                    <div class="col-sm-2">
                        <div class="form-group">
                            <label>品牌</label>
                            <input class="form-control" id="s-name">
                        </div>
                    </div>
                    <div class="col-sm-2">
                        <div class="form-group">
                            <label>品牌英文名</label>
                            <input class="form-control" id="s-enName">
                        </div>
                    </div>
                    <div class="col-sm-2">
                        <div class="form-group">
                            <label>品牌</label>
                            <input class="form-control" id="s-category">
                        </div>
                    </div>
                    <div class="col-sm-2">
                        <div class="form-group">
                            <label>上架状态</label>
                            <select class="form-control" id="s-status">
                                <option value="">全部</option>
                                <option value="1">已上架</option>
                                <option value="2">未上架</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-sm-4">
                        <label style="visibility: hidden">为了好看</label>
                        <div class="form-group">
                            <button type="button" id="clear" class="btn btn-default">清空</button>
                            <button type="button" id="search" class="btn btn-default">查询</button>
                        </div>
                    </div>
                </div>

                <div class="row" id="moreSearchRow" hidden>
                    <div class="col-sm-2">
                        <div class="form-group">
                            <label>品牌英文名</label>
                            <input class="form-control" id="s-upTime">
                        </div>
                    </div>
                    <div class="col-sm-2">
                        <div class="form-group">
                            <label>使用状态</label>
                            <select class="form-control" id="a-category1">
                                <option value="">全部</option>
                                <option value="0">使用中</option>
                                <option value="0">未使用</option>
                            </select>
                        </div>
                    </div>


                </div>
            </div>
        </div>

        <div class="box">
            <div class="box-header" >
                <div class="tableTitle pull-left" style="font-size: 14px">   品牌详情</div>


                <button class="btn btn-primary btn-xs pull-left" style="margin-left: 20px" data-toggle="modal" data-target="#myModal">    新增品牌</button>

                <button class="btn btn-danger btn-xs pull-left" style="margin-left: 10px">   删除</button>

            </div>
            <!-- /.box-header -->
            <div class="box-body">
                <div id="example1_wrapper" class="dataTables_wrapper form-inline dt-bootstrap">
                    <div class="row">

                    </div>
                    <div class="row">
                        <div class="col-sm-12">
                            <table id="dms-table" class="table table-bordered table-striped dataTable" role="grid"
                                   aria-describedby="example1_info">
                                <thead>
                                <tr role="row">
                                    <th  aria-controls="example1" rowspan="1"
                                         colspan="1" aria-sort="ascending"
                                         aria-label="Rendering engine: activate to sort column descending">商品ID
                                    </th>
                                    <th aria-controls="example1" rowspan="1" colspan="1"
                                        aria-label="Browser: activate to sort column ascending" >商品编号
                                    </th>
                                    <th aria-controls="example1" rowspan="1" colspan="1"
                                        aria-label="Platform(s): activate to sort column ascending">图片
                                    </th>
                                    <th aria-controls="example1" rowspan="1" colspan="1"
                                        aria-label="Engine version: activate to sort column ascending">商品名称
                                    </th>
                                    <th aria-controls="example1" rowspan="1" colspan="1"
                                        aria-label="CSS grade: activate to sort column ascending">销售价(元)
                                    </th>
                                    <th aria-controls="example1" rowspan="1" colspan="1"
                                        aria-label="CSS grade: activate to sort column ascending">新品
                                    </th>
                                    <th aria-controls="example1" rowspan="1" colspan="1"
                                        aria-label="CSS grade: activate to sort column ascending">热卖
                                    </th>
                                    <th aria-controls="example1" rowspan="1" colspan="1"
                                        aria-label="CSS grade: activate to sort column ascending">在售
                                    </th>
                                    <th aria-controls="example1" rowspan="1" colspan="1"
                                        aria-label="CSS grade: activate to sort column ascending">销售价
                                    </th>
                                    <th aria-controls="example1" rowspan="1" colspan="1"
                                        aria-label="CSS grade: activate to sort column ascending">操作
                                    </th>
                                    <th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1"
                                        aria-label="CSS grade: activate to sort column ascending" hidden>操作
                                    </th>
                                </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <!-- /.box-body -->
        </div>


    </section>

</div>

<div layout:fragment="js">
    <script th:inline="javascript">
        var oTable = $('#dms-table');
        var currentId;
        var authArray = [];

        $('#search').click(function (e) {
            e.preventDefault();
            oTable.DataTable().ajax.reload();
        });

        $('#clear').click(function () {
            reloadTable();
        });

        $('#modifyModalModify').on('click', modifyModal);

        $('#createModalAdd').on('click', createModal);

        function clearModal() {
            $('#c-username').val('');
            $('#c-password').val('');
            $('#c-password1').val('');
        }

        function createModal() {
            var username = $('#c-username').val();
            var password = $('#c-password').val();
            var password1 = $('#c-password1').val();

            var validArgs = {
                "请输入帐号": username,
                "请输入密码": password,
                "请输入确认密码": password1,
            };
            //验证是否为空
            if (!validateArgs(validArgs)) {
                return;
            }

            if (password != password1) {
                toastr.error('请确认两次密码是否一致');
                return;
            }

            $.ajax({
                url: '/admins',
                type: 'post',
                dataType: 'json',
                data: {
                    "username": username,
                    "password": password
                },
                success: function (data) {
                    if (data['code'] == 200) {
                        toastr.success('添加管理员成功');
                        $('#createModal').modal('hide');
                        clearModal();
                        redraw();
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    var jsonObj = JSON.parse(XMLHttpRequest.responseText);
                    if (XMLHttpRequest.status == 400) {
                        toastr.error(jsonObj['msg']);
                    }
                }
            })
        }

        function modifyModal() {
            var oldpassword = $('#m-oldpassword').val();
            var password = $('#m-password').val();
            var password1 = $('#m-password1').val();

            var validArgs = {
//                "请输入旧密码": oldpassword,
                "请输入新密码": password,
                "请输入确认新密码": password1,
            };
            //验证是否为空
            if (!validateArgs(validArgs)) {
                return;
            }

            if (password != password1) {
                toastr.error('确保两次密码一致');
                return;
            }

            $.ajax({
                url: '/admins/' + currentId,
                type: 'put',
                dataType: 'json',
                data: {
                    "oldpass": oldpassword,
                    "password": password
                },
                success: function (data) {
                    if (data['code'] == 200) {
                        toastr.success('修改密码成功');
                        $('#modifyModal').modal("hide");
                        redraw();
                    } else {
                        toastr.error('修改密码失败：' + data['msg']);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    var jsonObj = JSON.parse(XMLHttpRequest.responseText);
                    if (XMLHttpRequest.status == 400) {
                        toastr.error(jsonObj['msg']);
                    }
                }
            })
        }

        $('#dms-table').find('tbody').on('click', 'tr button.modify', function (e) {
            e.preventDefault();
            var table = oTable.DataTable();
            var data = table.row($(this).parents('tr')).data();

            $('#m-oldpassword').val('');
            $('#m-username').val(data.username);
            $('#m-password').val('');
            $('#m-password1').val('');

            currentId = data['id'];

            $('#modifyModal').modal("show");
        });

        $('#dms-table tbody').on('click', 'tr button.auth', function (e) {
            e.preventDefault();
            var table = oTable.DataTable();
            var data = table.row($(this).parents('tr')).data();
            $('#auth-username').val(data.username);
            currentId = data['id'];
            loadAdminRoles(currentId);
            authArray = [];

            $('#authModal').modal("show");
        });

        $('#dms-table tbody').on('click', 'tr button.delete', function (e) {
            e.preventDefault();
            var table = oTable.DataTable();
            var data = table.row($(this).parents('tr')).data();

            swal({
                title: "删除该管理员【" + data.username + "】",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#5ECD1E",
                confirmButtonText: "Yes, 确定",
                cancelButtonText: "No, 取消",
                closeOnConfirm: true,
                closeOnCancel: true
            }, function (isConfirm) {
                if (isConfirm) {
                    $.ajax({
                        url: "/admins/" + data['id'],
                        type: "delete",
                        dataType: "json",
                        success: function (data) {
                            if (data.code == 200) {
                                toastr.success("删除成功");
                            } else {
                                toastr.error(data.msg);
                            }
                            redraw();
                        }
                    });
                }
            });
        });

        function reloadTable() {
            resetForm('search-form');   //重置所有input select
            oTable.DataTable().ajax.reload();
        }

        function redraw() {
            oTable.DataTable().draw(false);
        }

        function generateBtns(data, type, full, meta) {
            var temp = '';
            if (full.username == 'root') {
                temp = '禁止操作root超级管理员';
            } else {
                temp =
                    '<div class="btn-group">' +
                    '<button class="modify btn btn-xs btn-info">修改密码</button>' +
                    '<button class="delete btn btn-xs btn-danger">删除</button>' +
                    '</div>';
            }

            return temp;
        }

        //加载管理员的权限组
        function loadAdminRoles(adminId) {
            $.ajax({
                url: "/admins/adminRoles",
                type: "get",
                data: "adminId=" + adminId,
                dataType: "json",
                success: function (data) {
                    if (data != null) {
                        var authRole = $('#auth-role');
                        authRole.html('');
                        authRole.append('<option value="-1">请选择权限组</option>');
                        $.each(data, function (index, val) {
                            authRole.append('<option value="' + val.id + '">' + val.description + '</option>');
                        })

                        var authGroup = $('#auth-group');
                        authGroup.html("");
                        $.each(data, function (index, val) {
                            if (val.checked) {
                                authArray.push(val.id + '');
                                authGroup.append('<span class="tag label label-default" data-ref="' + val.id + '">' + val.description + '<span ' +
                                    'data-role="remove"></span></span>');
                            }
                        })
                    }
                }
            });
        }

        //更新管理员的权限组
        function updateAdminRoles(adminId, roleIds) {
            $.ajax({
                url: "/admins/adminRoles",
                type: "post",
                data: "adminId=" + adminId + "&roleIds=" + roleIds,
                dataType: "json",
                success: function (data) {
                    if (data.code == 200) {
                        $('#authModal').modal("toggle");
                        toastr.success("管理员权限修改成功");
                    } else {
                        toastr.error(data.msg);
                    }
                }
            });
        }

        //添加权限组
        function addAuth() {
            var val = $('#auth-role').val();
            var option = $('#auth-role').find(":selected").text();
            if (val != -1) {
                var index = authArray.indexOf(val);
                if (index < 0) {
                    //如果找不到 则添加
                    authArray.push(val);
                    $('#auth-group').append('<span class="tag label label-default" data-ref="' + val + '">' + option + '<span ' +
                        'data-role="remove"></span></span>');
                }
            }
        }

        //移除权限组 $e 为 tag
        function remove($e) {
            var tagId = $e.attr('data-ref').trim();
//            for (var i in authArray) console.log(typeof authArray[i] + "," + authArray[i])
            var index = authArray.indexOf(tagId);
//            console.log("tagId:" + tagId + "," + index + "authArray:" + authArray);
            if (index >= 0) {
                authArray.splice(index, 1);
            }
            $e.remove();
        }

        function planify(data) {
            for (var i = 0; i < data.columns.length; i++) {
                column = data.columns[i];
                delete(column.search);
                delete(column.searchable);
                delete(column.orderable);
                delete(column.name);
                delete(column.data);
            }
            data.name = $('#s-name').val();
            data.enName = $('#s-enName').val();
            delete(data.search);
        }

        function dtinit() {
            var url = "/goods/brand/page";
            oTable.DataTable({
                serverSide: true,
                ordering: false,
                searching: false,
                stateSave: false,
                autoWidth: false,
                pagingType: "full_numbers",
                lengthMenu: [
                    [10, 25, 50, 100],
                    [10, 25, 50, 100]
                ],
                ajax: {
                    url: url,
                    type: 'GET',
                    data: function (data) {
                        planify(data);
                    }
                },
                columns: [
                    {
                        data: 'id',
                    },
                    {
                        data: 'name',
                    },
                    {
                        data: 'enName',
                    },
                    {
                        data: 'created',
                        render: function (data, type, full, meta) {
                            return renderDate(data);
                        }
                    },
                    {
                        data: 'created',
                        render: function (data, type, full, meta) {
                            return renderDate(data);
                        }
                    },
                    {
                        data: 'created',
                        render: function (data, type, full, meta) {
                            return renderDate(data);
                        }
                    },
                    {
                        data: 'created',
                        render: function (data, type, full, meta) {
                            return renderDate(data);
                        }
                    },
                    {
                        data: 'created',
                        render: function (data, type, full, meta) {
                            return renderDate(data);
                        }
                    },
                    {
                        data: 'created',
                        render: function (data, type, full, meta) {
                            return renderDate(data);
                        }
                    },

                    {
                        data: 'id',
                        render: function (data, type, full, meta) {
                            return generateBtns(data, type, full, meta);
                        }
                    }

                ],
                columnDefs: [{
                    targets: "_all",
                    defaultContent: "空"
                }, {
                    targets: "_all",
                    className: 'text-center',
                    orderable: false
                }],
                language: {
                    "lengthMenu": "每页 _MENU_ 条记录",
                    "zeroRecords": "<h4 class='text-center'>没有找到记录</h4>",
                    "info": "显示 _START_ 到 _END_ 行，总共 _TOTAL_ 行， 第 _PAGE_ 页 ( 共 _PAGES_ 页 )",
                    "infoEmpty": "无记录",
                    "infoFiltered": "(从 _MAX_ 条记录过滤1)",
                    "search": "查询：",
                    "paginate": {
                        "first": "首页",
                        "last": "尾页",
                        "previous": "上一页",
                        "next": "下一页"
                    }
                }
            });
        }

        $(document).ready(function () {
            dtinit();
            // 添加图片
            var option = {
                urlName: 'activity/cover/',     //用于掺入图片url
                uploaderName: 'uploader1',      //新建plupload对象名
                uploaderBtn: 'c-selectfiles',   //上传按钮id
                progressBtn: 'c-ossfile',       //进度条显示块id
                img: 'c-cover',                 //<img>的id
                img2: 'cc-cover'                //<input>图片url的id
            };
            imageUploader(option);

            // 修改图片
            var option2 = {
                urlName: 'activity/cover/',       //用于掺入图片url
                uploaderName: 'uploader2',        //新建plupload对象名
                uploaderBtn: 'm-selectfiles',     //上传按钮id
                progressBtn: 'm-ossfile',         //进度条显示块id
                gallery: 'm-imgGroup',            //图片组的id
                imgId: 'activityImg'   ,          //<img>标签id
                colmd:3
            };
            multipleUploader(option2);
            moveToLeft(option2);

        })


        $('#moreSearch').click(function (e) {
            if ($("#moreSearchRow").is(":hidden")) {
                $('#moreSearch').text("收起高级搜索")
                $("#moreSearchRow").show(500);    //如果元素为隐藏,则将它显现
            } else {
                $('#moreSearch').text("高级搜索")
                $("#moreSearchRow").hide(500);     //如果元素为显现,则将其隐藏
            }
        })

         function addBrand() {
                 var gallery = "";
                 $(".m-cover .mm-cover img").each(function () {
                     gallery = gallery + $(this).attr("src") + ",";
                 });


                 $.ajax({
                     type: "POST",
                     url: "/goods/brand/add",
                     data: {
                         "name": $("#a-name").val(),
                         "enName": $("#a-enName").val(),
                         "isNew":0,
                         "isShow":1,
                         "sortOrder":1,
                         "floorPrice":0,
                         "picUrl": $("#cc-cover").val(),
                         "listPicUrl": gallery,
                         "keywords": $("#a-keywords").val(),
                         "simpleDesc": $("#a-simpleDesc").val(),
                     },
                     success: function (result) {
                         if (result.code == 200) {
                             console.log(result.code);

                             $('#myModal').modal('hide');
                             toastr.success('添加成功');
                             redraw();
                         } else {
                             toastr.error(result.msg);
                         }
                     },
                     statusCode: {
                         400: function () {
                             toastr.warning('服务器忙,请稍后重试！');
                         }
                     }
                 });

         }
    </script>


</div>
</body>
</html>
